<template>
  <div>
    <!-- 搜索栏 ： 两个搜索框  搜索按钮  添加挂号按钮  批量删除   -->
	 <h2 style="font-size:16px">精准搜索</h2>
	<el-row>
	  <el-col :span="1"></el-col>
	  <el-col :span="4">
		   <el-input placeholder="请输入病历号" v-model="query.caseNumber"/>
	  </el-col>
	  <el-col :span="4">
	  		<el-input placeholder="请输入姓名" v-model="query.realName"/>
	  </el-col>
	  <el-col :span="2">
	  		<el-button type="primary" plain @click="getByPage">搜索</el-button>
	  </el-col>
	  <el-col :span="3">
	  		<el-button type="success" plain @click="toAddReg">新增挂号</el-button>
	  </el-col>
	  <el-col :span="3">
	  		<el-button type="danger" plain @click="handleBatchDel">批量删除</el-button>
	  </el-col>
	  
	  
    </el-row>


	<h2 style="font-size:16px">按条件筛选</h2>
	<el-row>
	  <el-col :span="1"></el-col>
	  <el-col :span="4">
		<!-- 1-已挂号 2-医生接诊 3-看诊结束 4-已退号 -->
		   <el-select placeholder="挂号状态" v-model="query.visitState">
				<el-option label="挂号状态" :value="null"></el-option>
				<el-option label="已挂号" :value="1"></el-option>
				<el-option label="医生接诊" :value="2"></el-option>
				<el-option label="看诊结束" :value="3"></el-option>
				<el-option label="已退号" :value="4"></el-option>
		   </el-select>
	  </el-col>
	  <el-col :span="4">
			<el-date-picker
				v-model="query.visitDate"
				type="date"
				value-format="YYYY-MM-DD"
				placeholder="挂号日期"
			/>
	  </el-col>
	  <el-col :span="4">
		<el-select
			v-model="query.departmentId"
			placeholder="挂号科室"
		>
		    <el-option :value="null" label="挂号科室"></el-option>
			<el-option v-for="dept in departmentList" 
							:key="dept.id" 
							:label="dept.deptName" 
							:value="dept.id" />
		</el-select>
	  </el-col>
	  
	  <el-col :span="2">
	  		<el-button type="primary" plain @click="getByPage">搜索</el-button>
		</el-col>
	  
    </el-row>

	<!-- 表格 -->
	<el-row>
	  <el-col :span="22">
		  
		<el-table :data="pb.records" 
		          stripe 
				  border
				  @selection-change="handleSelectionChange">
		  <el-table-column type="selection"  width="55" />
		  <el-table-column type="index" width="50" />
		  <el-table-column prop="caseNumber" label="病历号" width="100px"/>
		  <el-table-column prop="realName" label="姓名" width="120px"/>
		  <el-table-column prop="employee.realname" label="看诊医生" width="120px"/>
		  <el-table-column label="挂号状态" width="120px">
			<template #default="scope">
				<span style="color:green" v-if="scope.row.visitState==1"> 已挂号 </span>
				<span style="color:red" v-else-if="scope.row.visitState==2"> 医生接诊 </span>
				<span style="color:blue" v-else-if="scope.row.visitState==3"> 看诊结束 </span>
				<span style="color:gray" v-else-if="scope.row.visitState==4"> 已退号 </span>
			</template>
		  </el-table-column>
		  <el-table-column prop="visitDate" label="挂号时间" width="120px"/>
		  <el-table-column prop="department.deptName" label="看诊科室" width="120px"/>
		
		  <el-table-column label="操作" width="200px">
		        <template #default="scope">
		          <el-button 
					size="small" 
					:disabled="scope.row.visitState!=1"
					@click="changeVisitState(scope.row,4)">
		            退号
		          </el-button>
		          <el-button
		            size="small"
		            type="danger"
		            @click="showRegInfo(scope.row)"
		          >
		            查看
		          </el-button>
		        </template>
		      </el-table-column>
		</el-table>
		  
	  </el-col>
	  
	</el-row>  
	<!-- 分页组件 -->
	<el-row>
	  <el-col :span="6"></el-col>
	  <el-col :span="12">
		   <el-pagination
		        v-model:current-page="query.current"
		        v-model:page-size="query.size"
		        :page-sizes="[5, 8, 10, 20]"
		        layout="total, sizes, prev, pager, next, jumper"
		        :total="pb.total"
		        @size-change="getByPage"
		        @current-change="getByPage"
		      />
	  </el-col>
	  
	</el-row>  
	
	<!-- 编辑挂号信息的对话框  用于添加和修改 -->
	<el-dialog v-model="dialogFormVisible" title="编辑挂号信息" width="500" draggable>
		<el-form :model="form">
		  <el-form-item label="挂号账号" :label-width="formLabelWidth">
			<el-input v-model.trim="form.RegisterAccount" autocomplete="off" readonly/>
		  </el-form-item>
		  <el-form-item label="挂号名称" :label-width="formLabelWidth">
			  <el-input v-model.trim="form.RegisterName" autocomplete="off" />
		  </el-form-item>
		  <el-form-item label="挂号地址" :label-width="formLabelWidth">
		  	  <el-input v-model.trim="form.RegisterAddress" autocomplete="off" />
		  </el-form-item>
		  <el-form-item label="挂号简介" :label-width="formLabelWidth">
		  	  <el-input v-model.trim="form.RegisterExplain" autocomplete="off" />
		  </el-form-item>
		  <el-form-item label="主图上传" :label-width="formLabelWidth">
			  <el-upload
				  class="avatar-uploader"
				  :action="baseUrl+'/upload'"
				  :show-file-list="false"
				  :on-success="handleAvatarSuccess"
				  :before-upload="beforeAvatarUpload"
				  name="myFile"
				>
			  <img v-if="imageUrl" :src="imageUrl" class="avatar" />
			  <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
		    </el-upload>
		  </el-form-item>
		  <el-form-item label="起送价" :label-width="formLabelWidth">
		  	  <el-input-number v-model="form.startPrice" :min="5"/>
		  </el-form-item>
		  <el-form-item label="配送费" :label-width="formLabelWidth">
		  	  <el-input-number v-model="form.deliveryPrice" :min="5"/>
		  </el-form-item>
		  <el-form-item label="备注" :label-width="formLabelWidth">
		  	  <el-input v-model.trim="form.remarks" autocomplete="off" />
		  </el-form-item>
		</el-form>
		<template #footer>
		  <div class="dialog-footer">
			<el-button @click="dialogFormVisible = false">取消</el-button>
			<el-button type="primary" @click="addOrUpdate">
			  确认提交
			</el-button>
		  </div>
		</template>
  </el-dialog>

  <!-- 显示挂号信息 -->
  <el-dialog v-model="dialogInfoVisible" title="挂号信息详情" width="500" draggable>
	 <div>{{regInfo}}</div>
  </el-dialog>
	
  </div>
</template>

<script setup>
//引入http请求的通用方法
import httpRequest from '../../common/index.js';
import { onMounted, ref, getCurrentInstance } from 'vue';
import { ElMain, ElMessage,ElMessageBox, resultProps } from 'element-plus';
import { nanoid } from 'nanoid';
import { Plus } from '@element-plus/icons-vue'

  let {proxy} = getCurrentInstance();

  let baseUrl = proxy.$baseUrl;


	//所有门诊科室的列表
	const departmentList = ref([])

	//查询所有门诊科室
	const getDeptByType = ()=>{
		httpRequest(
			proxy,
			'get',
			'/department/type/门诊',
			null,
			(resultBean)=>{
				departmentList.value = resultBean.data;
			}
		)
	}

	//去新增挂号页面
	const toAddReg = ()=>{
		proxy.$router.push('/main/regfee/AddRegister')
	}


	//修改挂号状态
	const changeVisitState = (row,visitState)=>{
		httpRequest(
			proxy,
			'post',
			'/register/change/state',
			{
				id: row.id,
				visitState: visitState
			},
			resultBean=>{
				row.visitState = visitState;
				ElMessage.success('退号成功');
			}
		)
	}

	//挂号信息弹窗是否显示
	const dialogInfoVisible = ref(false);

	const regInfo = ref({});

	//@TODO  显示弹窗展示挂号信息
	const showRegInfo = (row)=>{
		regInfo.value = row;
		dialogInfoVisible.value = true;
	}


  //对话框是否显示
  let dialogFormVisible = ref(false);
  let formLabelWidth = ref('100px');
  
  //表单数据 添加和修改
  let form = ref({
	  RegisterAccount: '',
	  RegisterName: '',
	  RegisterAddress: '',
	  RegisterImg: '',
	  RegisterExplain: '',
	  startPrice: 0.0,
	  deliveryPrice: 0.0,
	  remarks: ''
  })
  
  //生成挂号账号的函数
  const generateAccount = ()=>{
	  let account = nanoid().replaceAll("_","").replaceAll("-","");
	  console.log(account);
	  let startIndex = Math.floor(Math.random()*10);
	  account = account.substring(startIndex,startIndex+9);
	  console.log(account);
	  return account;
  }
  
  //点新增挂号信息按钮弹出对话框
  const showDialog = ()=>{
	  
	  dialogFormVisible.value = true;
	  //数据清除
	  form.value = {
		  RegisterAccount: generateAccount(),
		  RegisterName: '',
		  RegisterAddress: '',
		  RegisterExplain: '',
		  RegisterImg: '',
		  startPrice: 0.0,
		  deliveryPrice: 0.0,
		  remarks: ''
	  };
	  //清空之前上传的图片的回显链接
	  imageUrl.value = '';
  }

  //分页+搜索条件
  let query = ref({
	  current: 1,
	  size: 5,
	  realName: '',
	  caseNumber: '',
	  departmentId: null,
	  visitDate: '',
	  visitState: null,
	  employeeId: 1
  })
  
  //分页对象 total  pages  data(集合)
  let pb = ref({
	  total: 0,
	  pages: 0,
	  records: []
  })

  //分页查询挂号信息
  const getByPage = ()=>{

	httpRequest(
			proxy,
			'post',
			'/register/page',
			query.value,
			(resultBean)=>{
				pb.value = resultBean.data;
			})


	//   proxy.$axios({
	// 	  method: 'post',
	// 	  url: '/register/page',
	// 	  data: query.value
	//   }).then(res=>{
	// 	  console.log(res);
	// 	  let resultBean = res.data;
	// 	  if(resultBean.code==200){
	// 		let pageBean = resultBean.data; 
	// 		pb.value = pageBean;// total  pages  data(集合)
	// 	  }else{
	// 		  ElMessage.error(resultBean.msg);
	// 	  }
	//   })
  }
  
  //添加或修改
  const addOrUpdate = ()=>{
	  proxy.$axios({
		  method: 'post',
		  url: '/Register',
		  data: form.value
	  }).then(res=>{
		  let resultBean = res.data;
		  if(resultBean.code == 200){
			  getByPage();
			  dialogFormVisible.value = false;
			  ElMessage.success('保存挂号信息成功');
		  }else{
			  ElMessage.error(resultBean.msg);
		  }
	  })
  }
  
  //处理数据回显
  const handleEdit = (RegisterId)=>{
	  console.log('回显：RegisterId----',RegisterId);
	  //根据id查询对应的实体数据
	  proxy.$axios({
		  method: 'get',
		  url: '/Register/'+RegisterId
	  }).then(res=>{
		  let resultBean = res.data;
		  if(resultBean.code == 200){
			  form.value = resultBean.data;
			  imageUrl.value = resultBean.data.RegisterImg; //回显之前的图片
			  dialogFormVisible.value = true;
		  }else{
			  ElMessage.error(resultBean.msg);
		  }
	  })
  }
  
  //处理删除
  const handleDelete = (RegisterId)=>{
	  console.log('删除：RegisterId----',RegisterId);
	  ElMessageBox.confirm(
	      '您确定要删除该挂号信息吗？',
	      '删除提示',
	      {
	        confirmButtonText: '确定',
	        cancelButtonText: '取消',
	        type: 'warning',
	      }
	    )
	      .then(() => {
			  
			  //确定删除
			  proxy.$axios({
				  method: 'delete',
				  url: '/Register/'+RegisterId
			  }).then(res=>{
				  let resultBean = res.data;
				  if(resultBean.code == 200){
					  ElMessage.success('删除成功');
					  getByPage();
				  }else{
					  ElMessage.error(resultBean.msg);
				  }
			  })
			  
	      })
	      .catch(() => {
	           ElMessage.info('取消删除');
	      })
  }
  
  // const selectable = (row,index)=>{
	 //  console.log('selectable',row,index);
	 //  return true;
  // }
  
  //选中项的id集合
  let selectOptions = ref([]);
  
  //表格中多选框选中或取消时会触发  也就是选中项变化
  const handleSelectionChange = (newSelection)=>{
	  console.log('选中项改变',newSelection);
	  selectOptions.value = []; //清空
	  newSelection.forEach((selOp)=>{
		  console.log(selOp.RegisterId);
		  selectOptions.value.push(selOp.RegisterId);
	  });
  }
  
  //批量删除的函数
  const handleBatchDel = ()=>{
	  console.log(selectOptions.value);
	  if(selectOptions.value.length==0){
		  ElMessage.info('请选中至少一条记录之后再进行删除');  
		  return;
	  }
	  
	  ElMessageBox.confirm(
	      '您确定要删除选中的挂号信息吗？',
	      '删除提示',
	      {
	        confirmButtonText: '确定',
	        cancelButtonText: '取消',
	        type: 'warning',
	      }
	    )
	      .then(() => {

			console.log(selectOptions.value);
			console.log(typeof(selectOptions.value));
			console.log(JSON.stringify(selectOptions.value));

			let str = JSON.stringify(selectOptions.value);
			str = str.substring(1,str.length-1);
	  			  
	  			  //确定删除
				proxy.$axios({
					method: 'post',
					url: '/Register/batch/'+str,
				}).then(res=>{
					let resultBean = res.data;
					if(resultBean.code == 200){
						ElMessage.success('删除成功');  
						getByPage();
					}else{
						ElMessage.error(resultBean.msg);
					}
				})
	  			
	  			  
	      })
	      .catch(() => {
	           ElMessage.info('取消删除');
	      })
  }
  
  //上传图片的回显链接
  let imageUrl = ref('');
  
  //上传成功之后的回调
  const handleAvatarSuccess = (response,uploadFile)=>{
	  ElMessage.success('上传成功');
	  console.log('上传成功，',response,uploadFile);
	  //负责上传完成 图片回显
	  imageUrl.value = response.data;
	  //将上传成功的链接放入form表单， 添加或修改时会携带到服务端
	  form.value.RegisterImg = response.data;
  }
  
  //上传之前预检文件
  const beforeAvatarUpload = (rawFile)=>{
	  //文件类型不符合要求 或者 文件大小超过要求  都不能上传
	  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
	      ElMessage.error('Avatar picture must be JPG format!')
	      return false
	    } else if (rawFile.size / 1024 / 1024 > 5) {
	      ElMessage.error('Avatar picture size can not exceed 5MB!')
	      return false
	    }
		//可以上传
	    return true
  }

  //*******更改删除状态************************** */
  const changeDelmark = (row)=>{

	httpRequest(
			proxy,
			'put',
			'/register/change/delmark',
			{
				id: row.id,
				delmark: row.delmark
			},
			(resultBean)=>{
				ElMessage.success("修改删除状态成功");
			})

	// proxy.$axios({
	// 	method: 'put',
	// 	url: '/register/change/delmark/',
	// 	data: {
	// 		id: row.id,
	// 		delmark: row.delmark
	// 	}
	// }).then(res=>{
	// 	let resultBean = res.data;
	// 	if(resultBean.code == 200){

	// 	}
	// })
  }
  
  onMounted(()=>{
	  getByPage();
	  getDeptByType();
  })


</script>

<style scoped>
	.avatar-uploader .avatar {
	  width: 100px;
	  height: 100px;
	  display: block;
	}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
}
</style>